//从storage里读取shiptype
var shiptypelist
shiptypelist = window.localStorage.getItem("shiptypelist")
if(shiptypelist){
  Project_ParamConfig.ShipTypeList= JSON.parse(shiptypelist)
}
//地图对象
var map = new L.Map('map', {
    center: new L.latLng([24, 106]),
    zoom: 4,
    minZoom: 2,
    maxZoom: 18,
    crs: L.CRS.EPSG3395,
    zoomControl: true,
    attributionControl: false,
    closePopupOnClick: false,
    doubleClickZoom: false
});

//底图图层
if(Project_ParamConfig.IsUseNetWorkCharMap) {
    var baseLayer = new L.tileLayer.ChartLayer2("http://m2.shipxy.com/tile.c?l=Na&m=o&z={z}&y={y}&x={x}", {
        id: Project_ParamConfig.baseLayer.id
    });
} else {
    var baseLayer = new L.tileLayer.ChartLayer(Project_ParamConfig.ChartLayerUrl, {
        id: Project_ParamConfig.baseLayer.id
    });
}
map.addLayer(baseLayer);

//区域开窗类
var AreaOpenWindow = function () {
    try {
        var data = this.getData();
    } catch(e) {
        console.error(e);
        return;
    }
    this._data = data;
    this.config = Project_ParamConfig.RealTargetConfig;
    this.isAjaxComplete = 0;
    this.map = map;
}

AreaOpenWindow.prototype = {

    constructor: AreaOpenWindow,

    start: function () {
        this.addRectangle();
        this.initTargetsLayer();
        this.updateTargtes();
    },

    addRectangle: function () {
        var bounds = this._data.bounds;
        var rect = this._rectlayer = L.rectangle(bounds, {});
        this.map.addLayer(rect);
        this.map.fitBounds(rect.getBounds(), { maxZoom: this._data.zoom });
    },

    initTargetsLayer: function () {
        if(this.map.hasLayer(this.targetsFeatrueGroup)) {
            this.map.removeLayer(this.targetsFeatrueGroup);
        }
        this.targetsFeatrueGroup = L.featureGroup().addTo(this.map);
        var targets = this._data.targets;
        for(var i = 0, len = targets.length; i < len; i++) {
            var marker = this.createMarker(targets[i]);
            this.targetsFeatrueGroup.addLayer(marker);
        }
    },

    updateTargtes: function () {
        this.getShipInfo();
        window.setInterval(function () {
            if(this.isAjaxComplete === 1) {
                this.getShipInfo();
            }
        }.bind(this), 5 * 1000);
    },

    getShipInfo: function () {
        var url = this.config.shipRealUrl,
            data = {
                limit: this.config.limit,
                timeout: this._data.timeout,
                mode: this._data.mode,
            };
        data = L.extend(data, this.getCurRectExtend());
        this.isAjaxComplete = 0;
        this._ajax = $.ajax({
            url: url,
            data: data,
            type: 'POST',
            dataType: 'json',
            context: this,
            success: this._ajaxsuccess,
            error: this._ajaxerror
        }).always(function () {
            this.isAjaxComplete = 1;
        }.bind(this));
    },

    _ajaxsuccess: function (res) {
        if(res.state !== 1) {
            return;
        }
        this.updateLayer(res);
    },

    _ajaxerror: function (error) {},

    updateLayer: function (data) {
        var newlist = this.convertShipList(data);
        this.removeInvalidTarget(newlist);
        this.updateAllTarget(newlist);
    },

    convertShipList: function (data) {
        var shiplist = data.msg.shipList;
        var newlist = [];
        for(var i = 0, len = shiplist.length; i < len; i++) {
            var targetobj = this.convertTargetObj(shiplist[i]);
            newlist.push(targetobj);
        }
        return newlist;
    },

    removeInvalidTarget: function (newlist) {
        var layers = this.targetsFeatrueGroup.getLayers();
        for(var i = 0, len = layers.length; i < len; i++) {
            var layer = layers[i];
            var dataobj = layer.options.data;
            if(!this.isContain(dataobj, newlist)) {
                this.targetsFeatrueGroup.removeLayer(layer);
            }
        }
    },

    updateAllTarget: function (newlist) {
        for(var i = 0, len = newlist.length; i < len; i++) {
            var obj = newlist[i];
            this.updateOneTarget(obj);
        }
    },

    updateOneTarget: function (obj) {
        var iscontain = false;
        var layers = this.targetsFeatrueGroup.getLayers();
        for(var i = 0, len = layers.length; i < len; i++) {
            var layer = layers[i];
            var data = layer.options.data;
            //如果当前图层有新目标，更新
            if(data.id === obj.id) {
                iscontain = true;
                var latlng = L.latLng(obj.lat, obj.lon);
                layer.options.data = L.extend(layer.options.data, obj);
                layer.setLatLng(latlng);
                layer.setRotationAngle(obj.dir);
                layer.unbindPopup();
                layer.bindPopup(this.getTargetInfo(obj), this.getPopupOptions());
                break;
            }
        }

        //如果当前图层没有新目标，添加（可以加上个数限制）
        // if (!iscontain && layers.length < this.config.limit) {
        //     var marker = this.createMarker(obj);
        //     this.targetsFeatrueGroup.addLayer(marker);
        //     marker.unbindPopup();
        //     marker.bindPopup(this.getTargetInfo(obj),this.getPopupOptions());
        // }
    },

    convertTargetObj: function (oneinfo) {
        var onetarget = {}
        onetarget.countryOrig = this.getDetialConvertName(oneinfo.co, 'countryOrig') // 国别country 中文（过滤）
        onetarget.countryOrig = oneinfo.co.replace(/@/g, '') // 监控统计需要原始的国家名
        onetarget.infotype = oneinfo.mt // 信息类型 int
        onetarget.infosrc = oneinfo.ms // 信息来源 int 0;1,2,3
        onetarget.num = oneinfo.nu // 目标编号num int
        onetarget.lon = parseFloat(oneinfo.lo / 600000) // 经度
        onetarget.lat = parseFloat(oneinfo.la / 600000) // 纬度
        onetarget.dir = parseFloat((oneinfo.di / 10).toFixed(1)) // 船航向 int
        onetarget.heading = oneinfo.he // 船首向 int
        onetarget.shipname = oneinfo.sn.replace(/@/g, '') || '' // 船名
        onetarget.shiptype = this.getDetialConvertName(oneinfo.st, 'ship_type') // 船舶类型 int（不过滤）
        onetarget.time = oneinfo.ti
        onetarget.speed = oneinfo.sp / 10 || ''
        // 自定义属性
        onetarget.id = this.getShipIdMode(oneinfo).id // 计算后的id，作为船舶的唯一id
        onetarget.mode = this.getShipIdMode(oneinfo).mode // 自定义 当前模式
        onetarget.qid = this.getShipQIdMode(oneinfo).qid // 组合后的id，作为查询时用
        onetarget.qmode = this.getShipQIdMode(oneinfo).qmode // 组合后的mode 查询时用
        onetarget.filterSrc = this.getShipSrc(oneinfo)
        return onetarget
    },

    getShipIdMode: function (targetobj) {
        var idmo = { id: null, mode: null }
        if(this._data.mode === 0) {
            idmo.id = targetobj.nu
            idmo.mode = 0
        } else {
            idmo.id = String(targetobj.ms) + String(targetobj.mt) + String(targetobj.nu)
            idmo.mode = targetobj.mt
        }
        return idmo
    },

    getShipQIdMode: function (targetobj) {
        var idmo = { qid: null, qmode: null }
        if(this._data.mode === 0) {
            idmo.qid = targetobj.nu
            idmo.qmode = 0
        } else {
            idmo.qid = targetobj.nu
            idmo.qmode = targetobj.ms * 256 + targetobj.mt
        }
        return idmo
    },

    getShipSrc: function (targetobj) {
        var src = -1
        if(targetobj.ms === 3 && targetobj.mt === 7) {
            src = 1
        } else if(targetobj.ms === 1 && (targetobj.mt === 3 || targetobj.mt === 4)) {
            src = 2
        } else if(targetobj.ms === 1 && targetobj.mt === 1) {
            src = 3
        } else if(targetobj.ms === 1 && targetobj.mt === 2) {
            src = 4
        } else if(targetobj.ms === 2 && (targetobj.mt === 3 || targetobj.mt === 4)) {
            src = 5
        } else if(targetobj.ms === 2 && targetobj.mt === 5) {
            src = 6
        } else if(targetobj.ms === 7 && targetobj.mt === 7) {
            src = 7
        } else if(targetobj.ms === 5 && targetobj.mt === 7) {
            src = 8
        } else if(targetobj.ms === 4 && (targetobj.mt === 3 || targetobj.mt === 4)) {
            src = 9
        } else if(targetobj.ms === 15) {
            src = 15
        }
        return src
    },

    getCurRectExtend: function () {
        var obj = {},
            bounds = this._rectlayer.getBounds(),
            southwest = bounds.getSouthWest(),
            northeast = bounds.getNorthEast();
        obj.ldlon = parseFloat(southwest.lng.toFixed(6));
        obj.ldlat = parseFloat(southwest.lat.toFixed(6));
        obj.rulon = parseFloat(northeast.lng.toFixed(6));
        obj.rulat = parseFloat(northeast.lat.toFixed(6));
        return obj;
    },

    createMarker: function (obj) {
        var latlng = L.latLng(obj.lat, obj.lon),
            icon = this.getTargetIcon(obj.shiptype);
        var options = {
            icon: icon,
            opacity: 1,
            rotationAngle: obj.dir,
            rotationOrigin: 'center center', //船舶旋转的参考点
            title: obj.shipname || '未知',
            data: obj
        };
        return L.marker(latlng, options);
    },

    getPopupOptions: function () {
        return { closeOnClick: true };
    },

    getTargetInfo: function (curobj) {
        var lat = this.latlngTodfmStr(curobj.lat, 'lat');
        var lng = this.latlngTodfmStr(curobj.lon, 'lng');
        var time = this.getTimeStrFromUnix(curobj.time);
        var info = "船舶编号：" + curobj.qid + "<br>" +
            "船名：" + curobj.shipname + "<br>" +
            "船舶类型：" + curobj.shiptype + "<br>" +
            "经度：" + lat + "<br>" +
            "纬度：" + lng + "<br>" +
            "航向：" + curobj.dir + "°<br>" +
            "船艏向：" + curobj.heading + "°<br>" +
            "时间：" + time + "<br>" +
            "船速：" + curobj.speed + "节<br>" +
            "国家/地区：" + curobj.countryOrig + "<br>" +
            "信息类型：" + this.getDetialConvertName(curobj.infotype, "orig_info_type") + "<br>" +
            "信息来源：" + this.getDetialConvertName(curobj.infosrc, "orig_info_source");
        return info;
    },

    getTargetIcon: function (type) {
        var type = type.toString(),
            icon = null;
        // switch(type) {
        // case "货船":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_1.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "搜救船":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_8.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "油轮":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_2.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "拖船":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_3.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "渔船":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_4.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "客船":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_5.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "军事船":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_6.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // case "其他":
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_7.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        //     break;
        // default:
        //     icon = L.icon({
        //         iconUrl: '../themes/images/shipIcons/target_7.png',
        //         iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
        //         iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
        //     });
        // }
        // return icon;
        for(var i=0;i<Project_ParamConfig.FilterDisplayConfig.staticShipTypeList.length;i++){
          if(i<8){
            if(type == Project_ParamConfig.FilterDisplayConfig.staticShipTypeList[i]){
              icon = 'target_'+(i+1)+'';
              icon = L.icon({
                      iconUrl: '../themes/images/shipIcons/target_'+(i+1)+'.png',
                      iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
                      iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
                  });
              return icon;
            }
            // else{
            //   icon = 'target_8'
            //   return icon;
            // }
          }
          else{
            icon = L.icon({
                    iconUrl: '../themes/images/shipIcons/target_8.png',
                    iconSize: [10, 22], //图标的大小，格式，第一个参数是宽度，第二个参数是高度
                    iconAnchor: [5, 11] //图标显示位置，例如宽度和高度是图标大小的一半，则经纬度的点正好在图标的中心点
                });
            return icon;
          }
        }
    },

    getDetialConvertName: function (code, type) {
        var res = ''
        if(code.toString) code = code.toString()
        if(type == 'ship_type') { // 船舶类型（不过滤）
            // switch(code) {
            // case '1':
            //     res = '货船'
            //     break
            // case '2':
            //     res = '搜救船'
            //     break
            // case '3':
            //     res = '油轮'
            //     break
            // case '6':
            //     res = '拖船'
            //     break
            // case '5':
            //     res = '渔船'
            //     break
            // case '7':
            //     res = '客船'
            //     break
            // case '8':
            //     res = '军事船'
            //     break
            // case '9':
            //     res = '渔政执法船'
            //     break
            // case '10':
            //     res = '风效应船'
            //     break
            // case '11':
            //     res = '高速船'
            //     break
            // }
            var shipName = Project_ParamConfig.ShipTypeList[code];
            // if(Project_ParamConfig.FilterDisplayConfig.shipTypeList.indexOf(shipName) !== -1){
                res = shipName;
            // }
            // else {
            //     res = '其他'
            // }
        } else if(type == 'country') { // 国别（过滤）
            // switch(code) {
            // case '中国':
            //     res = '中国'
            //     break
            // case '美国':
            //     res = '美国'
            //     break
            // case '英国':
            //     res = '英国'
            //     break
            // case '法国':
            //     res = '法国'
            //     break
            // case '俄罗斯':
            //     res = '俄罗斯'
            //     break
            // default:
            //     res = '其他'
            // }
            if(Project_ParamConfig.FilterDisplayConfig.shipFlagList.indexOf(code) !== -1){
                res = code;
            }
            else {
                res = '其他'
            }
        } else if(type == 'hwlx') { // 货物类型
            res = code
        } else if(type == 'status') { // 航行状态
            switch(code) {
            case '0':
                res = '在航（主机推动）'
                break
            case '1':
                res = '锚泊'
                break
            case '2':
                res = '失控'
                break
            case '3':
                res = '操纵受限'
                break
            case '4':
                res = '吃水受限'
                break
            case '5':
                res = '靠泊'
                break
            case '6':
                res = '搁浅'
                break
            case '7':
                res = '捕捞作业'
                break
            case '8':
                res = '靠船帆提供动力'
                break
            default:
                res = ''
            }
        } else if(type == 'fixing_device') { // 电子定位装置
            switch(code) {
            case '-1':
                res1 = '非法'
                break
            case '0':
                res = '默认'
                break
            case '1':
                res = 'GPS'
                break
            case '2':
                res = 'GLONASS'
                break
            case '3':
                res = 'GPS/GLONASS组合'
                break
            case '4':
                res = 'Loran-C'
                break
            case '5':
                res = 'Chayka'
                break
            case '6':
                res = '综合导航系统'
                break
            case '7':
                res = '观测'
                break
            case '8':
                res = '北斗'
                break
            case '9':
            case '10':
            case '11':
            case '12':
            case '13':
            case '14':
                res = '未使用'
                break
            case '15':
                res = '内部GNSS'
                break
            default:
                res = code
            }
        } else if(type == 'commun_state') { // 通信状态
            switch(code) {
            case '0':
                res = ''
                break
            case '1':
                res = 'SOTDMA'
                break
            case '2':
                res = 'ITDMA'
                break
            default:
                res = code
            }
        } else if(type == 'pos_accuracy') { // 船位精度
            switch(code) {
            case '0':
                res = ''
                break
            case '1':
                res = '定位误差大于10米'
                break
            case '2':
                res = '定位误差小于等于10米'
                break
            default:
                res = code
            }
        } else if(type == 'orig_info_source') { // 信息来源
            switch(code) {
            case '1':
                res = '农业部'
                break
            case '2':
                res = '海事局'
                break
            case '3':
                res = '海监'
                break
            case '4':
                res = '星载AIS'
                break
            case '5':
                res = '救捞局'
                break
            case '7':
                res = '保障局'
                break
            case '15':
                res = '综合'
                break
            default:
                res = code
            }
        } else if(type == 'orig_info_type') { // 信息类型
            switch(code) {
            case '1':
                res = 'Argos及海事卫星'
                break
            case '2':
                res = '北斗'
                break
            case '3':
                res = 'AIS静态'
                break
            case '4':
                res = 'AIS动态'
                break
            case '5':
                res = 'LRIT'
                break
            case '7':
                res = '船舶信息'
                break
            case '15':
                res = '综合态势信息'
                break
            default:
                res = code
            }
        }
        return res
    },

    getTimeStrFromUnix: function (time) {
        time = parseInt(time);
        if(isNaN(time)) {
            return "";
        }
        var newDate = new Date(time * 1000);
        // var newDate = new Date(time);
        var year = newDate.getFullYear();
        var month = (newDate.getMonth() + 1) < 10 ? "0" + (newDate.getMonth() + 1) : newDate.getMonth() + 1;
        var day = newDate.getDate() < 10 ? "0" + newDate.getDate() : newDate.getDate();
        var hours = newDate.getHours() < 10 ? "0" + newDate.getHours() : newDate.getHours();
        var minuts = newDate.getMinutes() < 10 ? "0" + newDate.getMinutes() : newDate.getMinutes();
        var seconds = newDate.getSeconds() < 10 ? "0" + newDate.getSeconds() : newDate.getSeconds();
        var ret = year + "-" + month + "-" + day + " " + hours + ":" + minuts + ":" + seconds;
        return ret;
    },

    latlngTodfm: function (val, latlngtype, iskeepCapacity, spointCount) {
        var resobj = [],
            dir;
        newval = parseFloat(val);
        var positiveNum = Math.abs(newval);
        var du = parseInt(positiveNum);
        var fen = parseInt(positiveNum * 60 - du * 60);
        var miao = positiveNum * 60 * 60 - fen * 60 - du * 60 * 60;
        if(typeof spointCount === 'undefined' || spointCount <= 0) { spointCount = 0; }
        // if(spointCount === 0) {
        //     miao = parseInt(miao);
        // } else {
        //     miao = miao.toFixed(spointCount);
        // }

        // 四舍五入
        miao = parseFloat(miao.toFixed(spointCount));
        if(miao >= 60) {
            miao = 0;
            miao = miao.toFixed(spointCount);
            fen += 1;
            if(fen >= 60) {
                fen = 0;
                du += 1;
            }
        }
        if(typeof iskeepCapacity === 'undefined') { iskeepCapacity = true; }
        if(iskeepCapacity) {
            if(latlngtype === 'lng') {
                if(du < 10) du = '00' + du;
                if(du >= 10 && du < 100) du = '0' + du;
            } else {
                if(du < 10) du = '0' + du;
            }
            if(fen < 10) fen = '0' + fen;
            if(miao < 10 && spointCount === 0) miao = '0' + miao;

        }
        if(latlngtype === 'lat') {
            if(newval < 0) dir = '南纬';
            else dir = '北纬';
        }
        if(latlngtype === 'lng') {
            if(newval < 0) dir = '西经';
            else dir = '东经';
        }
        resobj.push(du, fen, miao, dir);
        return resobj;
    },

    latlngTodfmStr: function (val, latlngtype, spointCount) {
        var res = this.latlngTodfm(val, latlngtype, spointCount);
        var str = res[3] + " " + res[0] + "°" + res[1] + "′" + res[2] + "″";
        return str;
    },

    getData: function () {
        var value = window.localStorage.getItem('openWindowAreaData');
        if(value !== null) {
            try {
                value = JSON.parse(value);
            } catch(e) {
                return value;
            }
        }
        return value;
    },

    isContain: function (obj, arr) {
        var iscontain = false;
        for(var i = 0, len = arr.length; i < len; i++) {
            if(arr[i].id === obj.id) {
                iscontain = true;
                break;
            }
        }
        return iscontain;
    }
};

//执行
$(function () {
    new AreaOpenWindow().start();
});
